import { request } from "./request";

function unwrap(response) {
  if (!response) {
    throw new Error("服务未响应");
  }
  const { code, msg, data } = response;
  // 后端成功时返回 code = 0
  if (code !== 0) {
    throw new Error(msg || "服务异常");
  }
  return data;
}

export async function fetchBanners(params = {}) {
  const res = await request({
    url: "/api/banners",
    method: "GET",
    data: params
  });
  return unwrap(res);
}

export async function fetchCategories() {
  const res = await request({ url: "/api/categories", method: "GET" });
  return unwrap(res);
}

export async function fetchWorks(params = {}) {
  const res = await request({
    url: "/api/works",
    method: "GET",
    data: params
  });
  return unwrap(res);
}

export async function fetchWorkDetail(workId) {
  if (!workId) {
    throw new Error("缺少作品编号");
  }
  const res = await request({ url: `/api/works/${workId}`, method: "GET" });
  return unwrap(res);
}

export async function fetchStudioProfile() {
  const res = await request({ url: "/api/studio", method: "GET" });
  return unwrap(res);
}

export async function createBooking(payload) {
  const res = await request({
    url: "/api/bookings",
    method: "POST",
    data: payload
  });
  return unwrap(res);
}

export async function fetchAvailableDates(params = {}) {
  const res = await request({
    url: "/api/bookings/available-dates",
    method: "GET",
    data: params
  });
  return unwrap(res);
}
